﻿using JQData.Core.DataModel;
using JQData.Core.DbModel;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace JQData.Application.DataFetch
{
    /// <summary>
    /// 数据缓存管理
    /// </summary>
    public class DataCacheManage(IDistributedCache _distributedCache, HotMoneyDataFetch _hotMoneyDataFetch
        , HotMoneyStockDataFetch _hotMoneyStockDataFetch, IRepository<HotMoney> _hmDb,
        ILogger<DataCacheManage> _log)
    {

        public async Task RefreshCache()
        {
            await RefreshHotMoneyCache();
            await RefreshHotMoneyStockCache();
        }

        public async Task RefreshHotMoneyStockCache()
        {
            // 刷新按股票汇总的游资数据缓存
            var list = await _hotMoneyStockDataFetch.Load(false);
            var cacheKey = GetCacheKey(CacheKeyType.StockHotMoneyData, null);


            await AddCache(_distributedCache, cacheKey, list);
            //加个延迟。。不然调用接口总是超限
            await Task.Delay(5000);
        }


        public async Task RefreshHotMoneyCache()
        {
            // 刷新游资数据缓存
            var list = _hmDb.Entities.ToList();
            var tasks = new List<Task>();
            var hotMoneyDataList = new List<HotMoneyData>();
            foreach (var item in list)
            {
                try
                {
                    var data = await _hotMoneyDataFetch.GetHotMoneyData(item.Id);
                    var cacheKey = GetCacheKey(CacheKeyType.HotMoneyData, item.Id);
                    await AddCache(_distributedCache, cacheKey, data);
                    hotMoneyDataList.Add(data);
                }
                catch (Exception ex)
                {
                    _log.LogError(ex, "刷新游资数据缓存失败: {HotMoneyId}", item.Id);
                }


            }

        }



        public static async Task AddCache(IDistributedCache cache, string key, object data)
        {
            var minutes = new Random().Next(100, 210);
            var options = new DistributedCacheEntryOptions()
                .SetAbsoluteExpiration(TimeSpan.FromMinutes(minutes));
            await cache.SetStringAsync(key, JsonSerializer.Serialize(data), options);
        }




        public static string GetCacheKey(CacheKeyType key, int? id)
        {
            return key switch
            {
                CacheKeyType.HotMoneyData => $"HotMoneyData:{id}",
                CacheKeyType.StockHotMoneyData => $"HotMoneyData:all",
                _ => throw new ArgumentOutOfRangeException(nameof(key), key, null)
            };
        }

    }


    public enum CacheKeyType
    {
        HotMoneyData,
        StockHotMoneyData
    }
}
